package com.example.ui.learn;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.ls.LSInput;

import com.example.downloadmanager.Downloader;
import com.example.huashangapp.HSApplication;
import com.example.huashangapp.R;
import com.example.huashangapp.R.color;
import com.example.huashangapp.R.drawable;
import com.example.net.AnalyzingJson;
import com.example.net.Communication;
import com.example.net.NetRequest;
import com.example.service.MainService;
import com.example.service.Mp3Service;
import com.example.service.Mp3Service.MyBinder;
import com.example.ui.MainActivity;
import com.example.ui.learn.util.Listen;
import com.example.ui.learn.util.MyClassroom;
import com.example.ui.learn.util.MyListViewAdapter4;
import com.example.ui.leftmenu.DownItem;
import com.example.ui.leftmenu.Item02View;
import com.example.ui.share.HsTalkActivity;
import com.example.ui.share.SRecommendActivity;
import com.example.ui.share.SeeActivity;
import com.example.util.AsyncLoadImage;
import com.example.util.Tools;

import android.R.integer;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
public class ListeningActivity extends Activity implements OnSeekBarChangeListener {
	private Button titleLeftBtn, titleRightBtn;
	private TextView titleText;
	private boolean isPlay = true;// 判断播放/暂停
	private ImageView iv_play, iv_next, iv_before, iv_download, iv_share;// 底部功能
	private Intent intent;
	private String data;
	private ArrayList<Listen> la_l = new ArrayList<Listen>();
	private ListView la_lv;
	private MyListViewAdapter4 la_adapter;
	private SeekBar la_seekbar;
	private int fileSize;
	private int downLoadFileSize;
	private String filename;
	private TextView mtvCurrentTime;// 当前时间
	private TextView mtvTotalTime;// 总时间
	public int currenttime;
	public int totaltime;  
	public static final String ISLISTENING="islistening";
	public static final String LISTEN="listen";

	public static MyBinder binder;
	private int id;// 歌曲id
	public static String uri = "";// 歌曲链接
	private  int pos = -1;
	private ArrayList<String> list_mp3 = new ArrayList<String>();
	private int localid = -1;
	public  static Boolean islo = false;
	private  String itemId = "";// 列表的id
	private ImageView imageView;
	private AsyncLoadImage asyncLoadImage;
	private String url = "", title, name;// 教师图片 标题 名字
	private TextView tvtitle;
	private TextView tvname;
	DownItem di=null;
	public static String filepath = "/sdcard/huashang/";// 歌曲下载的路径

	Timer t;
	public static int tag;// 2.huashang 1.muclassroom
	public static String itemUrl = ""; // 上次进
	public String blId;// 教师id
	private Notification notif;
	NotificationManager nm;
	AlertDialog infoad;
	AlertDialog.Builder bulider;
	ImageView ivNike;
	Intent intentMP3;
	private boolean isListening;
	private ListeningInfo listenInfo;
	public  boolean isnew=true;
	private IntentFilter filter;
	private boolean intro;

	@SuppressWarnings("static-access")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.a_listening);
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			filepath =Environment.getExternalStorageDirectory().toString()
					+ "/huashang/";
			Log.i("msg", "下载的路径"+filepath);
		}
		iv_play = (ImageView) findViewById(R.id.al_play);
		intent=getIntent();
		//intro=intent.getBooleanExtra("intro",false);
		listenInfo=(ListeningInfo)intent.getParcelableExtra(LISTEN);  
		tag=listenInfo.getListen_tag();
		url=listenInfo.getListen_thumb();
		title=listenInfo.getListen_title();
		name=listenInfo.getListen_name();
		blId=listenInfo.getListen_blId();
		isListening=intent.getBooleanExtra(ISLISTENING,false);
		itemId=listenInfo.getListen_itemId();
		di=new DownItem(this);
		if(HSApplication.HSlistInfo.getListen_uri()!=null
				&&!"".equals(HSApplication.HSlistInfo.getListen_uri())
				&&HSApplication.HSlistInfo.getListen_itemId().equals(itemId)){
			pos=HSApplication.HSlistInfo.getPos();
			la_adapter.currentPosition=pos;
		}
		getData();
	}
	private void getData() {
		bulider = new AlertDialog.Builder(ListeningActivity.this);
		bulider.setView(
				View.inflate(ListeningActivity.this, R.layout.onloading, null))
				.create();
		infoad = bulider.show();
			new Thread(listen_run).start();
	}
	@Override
	protected void onPause() {
		super.onPause();
	}
	Runnable listen_run = new Runnable() {
		@Override
		public void run() {
			switch (tag){
			case 1:
				data = NetRequest.Request_listen(listenInfo.getListen_itemId());
				break;
			case 2:
				data = NetRequest.Request_listen2(listenInfo.getListen_itemId());
				break;
			}
			if(data!=null){
			   la_l = AnalyzingJson.getdata_la(data);
			}
			h.sendEmptyMessage(3);
		}
			};
	private Button collectBtn;

	private void init() {
		if(Mp3Service.mp!=null){
			isPlay = Mp3Service.mp.isPlaying();
		}
			if(isPlay){
				iv_play.setBackgroundResource(R.drawable.al_suspend);
			}else{
				iv_play.setBackgroundResource(R.drawable.al_play);
			}
		asyncLoadImage = new AsyncLoadImage();
		imageView = (ImageView) findViewById(R.id.item01_list_img);
		imageView.setTag(url);
		asyncLoadImage.imageLoader.displayImage(url, imageView,asyncLoadImage.options);
		imageView.setTag(url);
		tvtitle = (TextView) findViewById(R.id.item01_list_text_title);
		tvname = (TextView) findViewById(R.id.item01_list_text_num);
		tvtitle.setText(title);
		tvname.setText(name);
		collectBtn=(Button)findViewById(R.id.collect);
		if(tag==1){
			new Thread(clickItem_run).start();
		}else{
			collectBtn.setVisibility(View.GONE);
		}
		inittop();
		mtvCurrentTime = (TextView) findViewById(R.id.tvcurrenttime);
		mtvTotalTime = (TextView) findViewById(R.id.tvtotaltime);
		la_adapter.currentPosition=pos;
		la_lv = (ListView) findViewById(R.id.al_lv);
		la_adapter = new MyListViewAdapter4(this, la_l);
		la_lv.setAdapter(la_adapter);
		
		la_lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long arg3) {
				if(la_l.get(position).getUrl()==null||"".equals(la_l.get(position).getUrl())){
					Toast.makeText(ListeningActivity.this, "地址为空",Toast.LENGTH_SHORT).show();
					return;
				}
				ivNike = (ImageView) v.findViewById(R.id.li_ivlisten);
				pos = position;
				id=Integer.parseInt(la_l.get(position).getId());
				listenInfo.setListen_uri(la_l.get(position).getUrl());
				listenInfo.setListen_id(la_l.get(position).getTitle());
				listenInfo.setPos(position);
				di.setUrl(la_l.get(pos).getUrl());
				play();
			}
		});
		la_seekbar = (SeekBar) findViewById(R.id.al_seekbar);
		iv_next = (ImageView) findViewById(R.id.al_next);
		iv_before = (ImageView) findViewById(R.id.al_before);
		iv_download = (ImageView) findViewById(R.id.al_ivdownload);
		iv_share = (ImageView) findViewById(R.id.al_ivshare);
		
		/*filter = new IntentFilter();
		filter.addAction(Tools.ACTION_CTIME);
		filter.addAction(Tools.ACTION_TTIME);
		filter.addAction(Tools.ACTION_COMPLETION);
		registerReceiver(receiver, filter);*/
		
		la_seekbar.setOnSeekBarChangeListener(this);
		titleLeftBtn.setOnClickListener(la_ocl);
		titleRightBtn.setOnClickListener(la_ocl);
		iv_play.setOnClickListener(la_ocl);
		iv_next.setOnClickListener(la_ocl);
		iv_before.setOnClickListener(la_ocl);
		iv_download.setOnClickListener(la_ocl);
		iv_share.setOnClickListener(la_ocl);
		
		if(!isListening){
			for (int i = 0; i < DownUtils.listUrl.size(); i++) {
				if(listenInfo.getListen_uri().equals(DownUtils.listUrl.get(i))){
					isnew=false;
					Downlistening();
					break;
				}
			}
		}else{
			filter = new IntentFilter();
			filter.addAction(Tools.ACTION_CTIME);
			filter.addAction(Tools.ACTION_TTIME);
			filter.addAction(Tools.ACTION_COMPLETION);
			registerReceiver(receiver, filter);
			isnew=false;
		}
	}

	Runnable clickItem_run = new Runnable() {
		@Override
		public void run() {
			data = NetRequest.Request_CheckCollet(listenInfo.getListen_itemId(),HSApplication.sp.getString("userid","").toString());
			Log.i("onitemcheck", data);
			String result = null;
			try {
				JSONObject j = new JSONObject(data);
				result = j.getString("response");
				intro=Boolean.parseBoolean(result);
				h.sendEmptyMessage(7);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};
	private void inittop() {
		titleLeftBtn = (Button) findViewById(R.id.layout_title_left_btn);
		titleRightBtn = (Button) findViewById(R.id.layout_title_right_btn);
		titleText = (TextView) findViewById(R.id.layout_title_middle_text);
		titleLeftBtn.setText("返回");
		titleText.setText("我正在听");
		titleRightBtn.setText("邀请讲师");
	}
	private Handler h = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
			case 2:
				Toast.makeText(ListeningActivity.this, "下载完成",
						Toast.LENGTH_LONG).show();
			case 3:
				infoad.dismiss();
				init();
				break;
			case 4:
				getData();
				break;
			case 5:
				collectBtn.setBackgroundResource(R.drawable.collect3);
				collectBtn.setOnClickListener(null);
				Toast.makeText(ListeningActivity.this, "恭喜收藏成功！",Toast.LENGTH_SHORT).show();
				break;
			case 7:
				if (intro) {
					collectBtn.setBackgroundResource(R.drawable.collect3);
					collectBtn.setOnClickListener(null);
					collectBtn.setVisibility(View.VISIBLE);
				}else{
					collectBtn.setBackgroundResource(R.drawable.collect_btn);
					collectBtn.setOnClickListener(la_ocl);
					collectBtn.setVisibility(View.VISIBLE);
				}
				break;
			}
		};
	};
	

	@Override
	protected void onRestart() {
		super.onRestart();
	}
	@Override
	protected void onDestroy() {
		if(!isnew){
			unregisterReceiver(receiver);
		}
		super.onDestroy();
	}
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		if (fromUser&&!isnew) {
			iv_play.setImageResource(R.drawable.al_suspend);
			intentMP3= new Intent();
			intentMP3.putExtra("musicId",listenInfo.getListen_id());
			intentMP3.putExtra("uri", listenInfo.getListen_uri());
			intentMP3.putExtra("progress", progress);
			intentMP3.putExtra("mode", Tools.PROGRESS);
			MainService.myBinder.startMp3Service(intentMP3);
		}
	}
	public BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Tools.ACTION_CTIME)) {// 获取当前时间
				currenttime = intent.getIntExtra("currentTime", -1);
				mtvCurrentTime.setText(Tools.format(currenttime));
				la_seekbar.setProgress(currenttime);

			} else if (action.equals(Tools.ACTION_TTIME)) {// 获取总时间
				totaltime = intent.getIntExtra("totaltime", -1);
				mtvTotalTime.setText(Tools.format(totaltime));
				la_seekbar.setMax(totaltime);

			} else if (action.equals(Tools.ACTION_COMPLETION)) {// 当一首歌播放完以后
				int loopmode = intent.getIntExtra("loop", -1);
				switch (loopmode) {
				case Tools.LOOP_ORDER:// 顺序播放
				//	ivNike.setVisibility(View.VISIBLE);
					next();
					break;
				default:
					break;
				}
			}
		}
	};
	 /**
	   * 判断是否已经下载过的
	   * @param uri 判断的地址
	   * @return
	   */
	public Boolean checkFile(){
		 Boolean isdowned=false;
		String lisuri="";
		if("".equals(listenInfo.getListen_uri())){
			Toast.makeText(ListeningActivity.this, "请选择课程",
					Toast.LENGTH_SHORT).show();
			return true;
		}
		lisuri=listenInfo.getListen_uri().substring(listenInfo.getListen_uri().lastIndexOf("/")+1);
		for (String file : DownUtils.downUrl) {
			if(file==null){
				continue;
			}
			String Downname= file.substring(file.lastIndexOf("/") + 1);
			if(lisuri.equals(file)){
				Toast.makeText(ListeningActivity.this, "该音频正在下载中",
						Toast.LENGTH_SHORT).show();
				return true;
			}
		}
			String lisname= listenInfo.getListen_uri().substring(listenInfo.getListen_uri().lastIndexOf("/") + 1);
			File f = new File(filepath);
			if (f.exists()) {
				searchFiles(f);
			}
			for (int i = 0; i < list_mp3.size(); i++) {
				if (lisname.equals(list_mp3.get(i))) {
					Toast.makeText(ListeningActivity.this, "该音频已经下载过",
							Toast.LENGTH_SHORT).show();
					isdowned=true;
				}
			}
			
		return isdowned;
	}

	OnClickListener la_ocl = new OnClickListener() {
		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.al_ivshare:
				Intent i = new Intent();
				i.putExtra("imageUrl",listenInfo.getListen_thumb());
				i.putExtra("title",listenInfo.getListen_title());
				i.putExtra("name", listenInfo.getListen_name());
				i.putExtra("musicUrl",listenInfo.getListen_uri());
				i.setClass(ListeningActivity.this, ShareActivity.class);
				startActivity(i);
				break;
			case R.id.al_ivdownload:
				if(checkFile()){
					return;
				}else{
				if (!isWIFI()) {
					return;
				}
				Down_Mp3();
				Intent intent=new Intent();
				Bundle bd=new Bundle();
				bd.putInt("moveView", 10);
				intent.putExtras(bd);
				intent.setClass(ListeningActivity.this,MainActivity.class);
				startActivity(intent);
				finish();	
				}
				break;
			case R.id.al_play:
				if (!"".equals(listenInfo.getListen_uri())&&!isnew) {
					if (!Mp3Service.mp.isPlaying()){
						 continiuPlay();
					} else {
						pause();
					}
				}else {
					Toast.makeText(ListeningActivity.this, "请选择",
							Toast.LENGTH_SHORT).show();
					return;
				}
				break;
			case R.id.al_before:
				before();
				break;
			case R.id.al_next:
				next();  
				break;
			case R.id.layout_title_left_btn:
				finish();
				break;

			case R.id.layout_title_right_btn:
				
				if (!la_l.isEmpty()) {
					switch (tag) {
					case 1:
						Intent cca_l = new Intent();
						cca_l.putExtra("tid",listenInfo.getListen_blId());
						cca_l.putExtra("title", listenInfo.getListen_title());
						cca_l.putExtra("name", listenInfo.getListen_name());
						cca_l.setClass(ListeningActivity.this, InviteActivity.class);
						startActivity(cca_l);
						finish();
						break;
					case 2:
						Intent cca_tolc = new Intent();
						cca_tolc.putExtra("tid",listenInfo.getListen_blId());
						cca_tolc.putExtra("tName", listenInfo.getListen_name());
						cca_tolc.setClass(ListeningActivity.this, SeeActivity.class);
						startActivity(cca_tolc);
						finish();
						break;
					}
				}
				break;
			case R.id.collect:
				if(itemId!=null){
					collect(itemId);
				}else{
					Toast.makeText(ListeningActivity.this, "请返回上一页重新选择",
							Toast.LENGTH_SHORT).show();
					return;
				}
				break;
			default:
				break;
			}
		}
	};
	
	/**
	 * 下一首
	 */
	private void next() {
		if(isnew){
			Toast.makeText(ListeningActivity.this,"请选择",Toast.LENGTH_SHORT).show();
			return;
		}
		getListenPosition(2);
		play();
	}
/**
 * 上一首
 */
	private void before() {
		if(isnew){
			Toast.makeText(ListeningActivity.this,"请选择",Toast.LENGTH_SHORT).show();
			return;
		}
		getListenPosition(1);
		play();
	}
	/**
	 * 继续播放
	 */
  public void continiuPlay(){
	  if(isnew){
			Toast.makeText(ListeningActivity.this,"请选择",Toast.LENGTH_SHORT).show();
			return;
		}
	  getListenPosition(3);
	  play();
  }
	/**
	 * 下载完成后播放的
	 * @param uri
	 * @param la_l
	 */
	public void Downlistening(){
		/*Handler downlishandler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					play();
					break;
				default:
					break;
				}
				
				super.handleMessage(msg);
			}
			
		};*/
		String downName=listenInfo.getListen_uri().substring(listenInfo.getListen_uri().lastIndexOf("/")+1);
		for (int i = 0; i <la_l.size(); i++) {
			String listname=la_l.get(i).getUrl().substring(la_l.get(i).getUrl().lastIndexOf("/")+1);
			if(downName.equals(listname)){
				listenInfo.setPos(i);
				play();
				  break;
			}
		}
	}
	/**
	 ** 暂停操作   
	 */
	private void pause() {
		iv_play.setImageResource(R.drawable.al_play);
		intentMP3=new Intent();
		intentMP3.putExtra("musicId",  HSApplication.HSlistInfo.getListen_id());
		intentMP3.putExtra("uri",  HSApplication.HSlistInfo.getListen_uri());
		intentMP3.putExtra("mode", Tools.PAUSE);
		MainService.myBinder.startMp3Service(intentMP3);
	}
	/**
	 *播放音频；
	 */
	@SuppressWarnings("static-access")
	private void play() {
		iv_play.setImageResource(R.drawable.al_suspend);
		intentMP3= new Intent();
		intentMP3.putExtra("musicId",listenInfo.getListen_id());
		intentMP3.putExtra("uri", listenInfo.getListen_uri());
		HSApplication.HSlistInfo.setListen_blId(this.listenInfo.getListen_blId());
		HSApplication.HSlistInfo.setListen_id(this.listenInfo.getListen_id());
		HSApplication.HSlistInfo.setListen_itemId(this.listenInfo.getListen_itemId());
		HSApplication.HSlistInfo.setListen_name(this.listenInfo.getListen_name());
		HSApplication.HSlistInfo.setListen_tag(this.listenInfo.getListen_tag());
		HSApplication.HSlistInfo.setListen_thumb(this.listenInfo.getListen_thumb());
		HSApplication.HSlistInfo.setListen_title(this.listenInfo.getListen_title());
		HSApplication.HSlistInfo.setListen_uri(this.listenInfo.getListen_uri());
		HSApplication.HSlistInfo.setPos(this.listenInfo.getPos());
		intentMP3.putExtra("mode", Tools.PLAY);
		isnew=false;
		filter = new IntentFilter();
		filter.addAction(Tools.ACTION_CTIME);
		filter.addAction(Tools.ACTION_TTIME);
		filter.addAction(Tools.ACTION_COMPLETION);
		registerReceiver(receiver, filter);
		MainService.myBinder.startMp3Service(intentMP3);
		//this关键字不指定的话没有选中
		la_adapter.currentPosition = this.listenInfo.getPos();
		la_adapter.notifyDataSetChanged();
	}
	/**
	 * 搜索下载的文件夹
	 * @param f
	 */
	private void searchFiles(File f) { // 搜索指定文件夹中的所有MP3文件
		list_mp3.clear();
		File files[] = f.listFiles();
		for (File tempF : files) {
			if(tempF==null){
				continue;
			}
			if (tempF.isDirectory()) {
				searchFiles(tempF);
			} else {
				String path = tempF.getPath();
				String fpath = path.substring(path.lastIndexOf(".") + 1,
						path.length());
				if (fpath.equals("mp3")) {
					String mp3 = path.substring(path.lastIndexOf("/") + 1);
					list_mp3.add(mp3);
				}
			}
		}
	}

/**
 * 下载当前选中的音频
 */
	public void Down_Mp3(){
		initDownItem();
		String newItem=listenInfo.getListen_uri();
		// 如果这个连接的下载任务还没有开始，就创建一个新的下载任务启动下载，并这个下载任务加到下载列表中
			DownUtils.downUrl.add(newItem);
			DownUtils.listDownItem.put(newItem, di);
				Downloader downloader = new Downloader(newItem, filepath,1,this,new DownHandler());
				DownUtils.downloaders.put(newItem,downloader);
				if(DownUtils.downIngCount<DownUtils.downCount){
					DownUtils.listDownItem.get(newItem).isDowned=true;
					downloader.init();
					Downloader.dao.saveInfos(downloader.infos,listenInfo);
					DownUtils.downIngCount++;
					}else{
				    Downloader.dao.saveListenDown(listenInfo);
					}
	}
	/**
	 * 初始化下载项的文本和url
	 */
	public void initDownItem(){
		if(pos>=0){
		di.setTitle(listenInfo.getListen_title());
		di.setName(listenInfo.getListen_name());  
		di.setSub_title(la_l.get(pos).getTitle());
		di.setUrl(listenInfo.getListen_uri());
		di.setAsyncTask(new DownHandler());
		di.setPic_Url(listenInfo.getListen_thumb());
		di.setTer_Id(listenInfo.getListen_blId());   
		di.setColum_Id(listenInfo.getListen_itemId());
		di.setTag(listenInfo.getListen_tag());
		di.setIsCollet(intro);
		}
	}
	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		
	}
	boolean netWork;
	/**
	 * 
	 * 判断网络类型是否是wifi
	 * @return
	 */
	public boolean isWIFI(){
		 netWork=false;
		String  net = MainService.setNetworkType(this);
		if ("".equals(net)) {
			new AlertDialog.Builder(this)
			.setTitle("当前没有可用的网络")
			.setMessage("请开启网络")
			.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog,
								int which) {
							 netWork=false;
						}
					}).show();
		} else if("wifi".equals(net)){
					netWork=true;
		}else{
			new AlertDialog.Builder(ListeningActivity.this)
					.setTitle("当前不是wifi环境!")
					.setMessage("确认要继续下载吗?")	
					.setNegativeButton(
							"取消",
							new android.content.DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									 netWork=false;
								}
							})
					.setPositiveButton(
							"确定",
							new android.content.DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									netWork=true;
								}
							}).show();
		}
	return netWork;
	}
	/**
	 * 收藏课程
	 * @param id
	 */
	public void collect(final String id){
		new Thread(new Runnable() {

			@Override
			public void run() {
				String data = null;
				if (!intro) {
					data = NetRequest.Request_addCourse(listenInfo.getListen_itemId());
				} 
				String result = AnalyzingJson
						.getcontent_result(data);
				if (result.equals("true")) {
						h.sendEmptyMessage(5);
				} else if(result.equals("exist")){
					h.sendEmptyMessage(5);
				}
			}
		}).start();
	}

	/**
	 * 播放控制
	 * @param la_l
	 * @param pos
	 */
	public void getListenPosition(int isNextOrBefore){
		String lisname="";
		if(HSApplication.HSlistInfo.getListen_uri()!=null&&!"".equals(HSApplication.HSlistInfo.getListen_uri())){
		 lisname=HSApplication.HSlistInfo.getListen_uri().substring(HSApplication.HSlistInfo.getListen_uri().lastIndexOf("/")+1);
		}
		switch (isNextOrBefore) {
		case 1://上一首
			for (int i = 0; i <la_l.size(); i++) {
				String listname=la_l.get(i).getUrl().substring(la_l.get(i).getUrl().lastIndexOf("/")+1);
				if(!"".equals(lisname)&&lisname.equals(listname)){
					if(i==0){
						Toast.makeText(ListeningActivity.this,"当前已经是第一项了",Toast.LENGTH_SHORT).show();
						return;
					}
					listenInfo.setListen_uri(la_l.get(i-1).getUrl());
					listenInfo.setListen_id(la_l.get(i-1).getTitle());
					listenInfo.setPos(i-1);
					  break;
				}
			}
			break;
		case 2://下一首；
			for (int i = 0; i <la_l.size(); i++) {
				String listname=la_l.get(i).getUrl().substring(la_l.get(i).getUrl().lastIndexOf("/")+1);
				if(!"".equals(lisname)&&lisname.equals(listname)){
					if(i>=la_l.size()-1){
						Toast.makeText(ListeningActivity.this,"当前已经是最后一项了",Toast.LENGTH_SHORT).show();
						return;
					}
					listenInfo.setListen_uri(la_l.get(i+1).getUrl());
					listenInfo.setListen_id(la_l.get(i+1).getTitle());
					listenInfo.setPos(i+1);
					  break;
				}
			}
			break;
		case 3://当前的
			for (int i = 0; i <la_l.size(); i++) {
				String listname=la_l.get(i).getUrl().substring(la_l.get(i).getUrl().lastIndexOf("/")+1);
				if(!"".equals(lisname)&&lisname.equals(listname)){
					listenInfo.setListen_blId(HSApplication.HSlistInfo.getListen_blId());
					listenInfo.setListen_uri(HSApplication.HSlistInfo.getListen_uri());
					listenInfo.setPos(i);
					  break;
				}
			}
			break;
		
		default:
			break;
		
	}
}
}